<!-- eslint-disable max-len -->
<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter editTestFormBox h100 newEditStyle rightDrawerWithoutCol"
  >
    <!-- 表单填写的基本信息 -->
    <div class="editTestFormBoxTop">
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('测试任务')" class="customFormModelItem" style="margin-bottom:0">
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row class="editTestFormBoxFirstRow" :gutter="40">
        <!-- 升级类型 -->
        <a-col :md="12" :sm="12">
          <a-form-model-item prop="type">
            <template #label>
              <span>{{ $t('upgradeType') }}</span>
              <question-mark-tip
                :tip-title="$t(upgradeTriggerType === 'USER' ? 'testUserTaskUpgradeTypeTip' : 'testAutoTaskUpgradeTypeTip')"
                :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="upgradeTriggerType">
              <a-radio :key="9" value="USER">{{$t('usersj')}}</a-radio>
              <a-radio :key="8" value="AUTO">{{$t('zdsj')}}</a-radio>
<!--              <a-radio-->
<!--                v-for="(item) in testTaskType"-->
<!--                :key="item.id"-->
<!--                :value="item.value"-->
<!--              >-->
<!--                {{ $t(item.name) }}-->
<!--              </a-radio>-->
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <!-- 强制升级 -->
          <a-form-model-item
            prop="forceUpgrade"
            key="forceUpgrade"
            v-if="upgradeTriggerType === 'USER'"
          >
            <template #label>
              <span>{{ $t('isQzsj') }}</span>
              <question-mark-tip :tip-title="$t('forceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.forceUpgrade" >
              <a-radio
                v-for="(item,index) in forceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- 静默升级 -->
          <a-form-model-item
            key="silenceUpgrade"
            v-else
            prop="silenceUpgrade"
          >
            <template #label>
              <span>{{ $t('sfjmsj') }}</span>
              <question-mark-tip :tip-title="$t('silenceUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.silenceUpgrade" >
              <a-radio
                v-for="(item,index) in slienceUpgradeType"
                :key="index"
                :value="item.value"
              >
                {{ $t(item.name) }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row class="editTestFormBoxFirstRow" :gutter="40">
        <a-col :md="12" :sm="12" v-if="upgradeTriggerType === 'USER' && testType === 'develop' && formData.isEqualUpgrade != true">
          <!-- 是否自由烧写 -->
          <a-form-model-item
            prop="freeBurning"
            key="freeBurning"
          >
            <template #label>
              <span>是否自由烧写</span>
              <question-mark-tip tip-title="自由刷写不检验软件升级的适配性。容易误刷软件，请谨慎适用！" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.freeBurning" >
              <a-radio key="yes" :value="1">{{ $t('yes') }}</a-radio>
              <a-radio key="no" :value="0">{{ $t('no') }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <a-col :md="12" :sm="12">
          <!-- 平刷 -->
          <a-form-model-item
            prop="equalUpgrade"
            key="equalUpgrade"
            v-if="testType === 'develop'"
          >
            <template #label>
              <span>{{ $t('isEqualUpgrade') }}</span>
            </template>
            <a-radio-group v-model="formData.isEqualUpgrade" :disabled="disabled">
              <a-radio key="yes" :value="true">{{ $t('yes') }}</a-radio>
              <a-radio key="no" :value="false">{{ $t('no') }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row class="editTestFormBoxFirstRow" v-if="upgradeTriggerType === 'USER' && testType === 'develop' && formData.isEqualUpgrade != true" :gutter="40">
        <a-col :md="12" :sm="12">
          <!-- 循环升级 -->
          <a-form-model-item
            prop="isCircleUpgrade"
            key="isCircleUpgrade"
          >
            <template #label>
              <span>{{ $t('是否循环升级') }}</span>
              <question-mark-tip :tip-title="$t('circleUpgradeTip')" :popupContainer="getPopupContainer">
              </question-mark-tip>
            </template>
            <a-radio-group v-model="formData.isCircleUpgrade" :disabled="disabled">
              <a-radio key="yes" :value="true">{{ $t('yes') }}</a-radio>
              <a-radio key="no" :value="false">{{ $t('no') }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
        <!-- 循环升级策略 -->
        <a-col v-if="formData.isCircleUpgrade === true" :md="12" :sm="12">
          <a-form-model-item prop="circleStrategyId" key="circleStrategyId1" >
            <template #label>
              {{ $t('circularUpgradeStrategy') }}
              <question-mark-tip
                :tip-title="$t('circularUpgradeStrategyTip')"
                :popupContainer="getPopupContainer"
              ></question-mark-tip>
            </template>
            <strategy-select
              :time="time"
              :query="stratetySelectQuery"
              :version-type="testType"
              :upgrade-trigger-type="upgradeTriggerType"
              :default-strate-id="formData.circleStrategyId"
              @changeoption="selectCircleStrategy"
            ></strategy-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row class="editTestFormBoxFirstRow" :gutter="40">
        <!-- 唤醒通道 -->
        <a-col v-if="upgradeTriggerType === 'AUTO' && testType === 'develop'" :md="12" :sm="12">
          <a-form-model-item :label="$t('hxtd')" prop="factoryChannel">
            <factory-channel-select
              :default-value="formData.factoryChannel"
              @changeoption="changeoption($event,'factoryChannel')"
            >
            </factory-channel-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row class="editTestFormBoxFirstRow" :gutter="40">
        <!-- 测试名称 -->
        <a-col :md="12" :sm="12">
          <a-form-model-item :label="$t('campaignName')" prop="name">
            <a-input style="width:80%" v-model="formData.name" />
          </a-form-model-item>
        </a-col>
        <!-- 升级策略 -->
        <a-col :md="12" :sm="12" class="sjclStyle">
          <a-form-model-item class="sjclSelect" :label="$t('sjcl')" prop="strategyId">
            <template v-if="strategyName">
              <span style="padding-right:10px;">{{strategyName}}</span>
              <a-tooltip title="清除">
                <a-button type="link" @click="() => changeStrategy('')"  style="margin-right:10px;">
                  <a-icon type="close"/>
                </a-button>
              </a-tooltip>
              <a-tooltip :title="$t('detail')">
                <a-button @click="showStrategy">
                  <i class="iconfont icon-chakanxiangqing1"></i>
                </a-button>
              </a-tooltip>
            </template>
            <auth-button type="info" v-if="!strategyName" :auth="strategyPerms[testType].USER.fotaSjcl.view"
                        @click="()=>{$refs.strategyTableSelector.setSelectedRowKey(formData.strategyId);$refs.strategyTableSelector.visible=true}"
                        style="margin-right: 10px;">
              {{ $t('select') }}
            </auth-button>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row class="editTestFormBoxFirstRow" :gutter="40">
        <a-col :md="12" :sm="12" v-if="upgradeTriggerType === 'AUTO'">
          <!-- 超时时长 -->
          <a-form-model-item :label="$t('timeout')+'(分钟)' " prop="duration">
            <a-input-number
              style="width: 80%"
              v-model="formData.duration"
              :placeholder="$t('pleaseInput')+$t('timeout')"
            ></a-input-number>
          </a-form-model-item>
        </a-col>
        <!-- 任务有效期 -->
        <a-col :md="12" :sm="12" v-if="upgradeTriggerType === 'USER'">
          <a-form-model-item :label="$t('rwyxq')" prop="expirationDate">
            <a-range-picker
              v-model="formData.expirationDate"
              :disabled-date="disabledDate"
              :disabledTime="disabledEndTime"
              :show-time="{ format: 'HH:mm' }"
              @ok="confirmDates"
              format="YYYY-MM-DD HH:mm"
              style="width: 80%"
              :placeholder="['开始时间','结束时间']"/>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- TODO liangminglong -->
      <a-form-model-item :label="$t('yuyueshengjie')" prop="" v-if="upgradeTriggerType === 'AUTO'">
        <div class="editTestFormBoxTableList">
          <a-table  :dataSource="appointTimeDataSource" :columns="appointTimeColumns" :pagination="false" :table-layout="'fixed'">
            <template slot="appointTime" slot-scope="text,record">
              <a-range-picker v-if="currentRecord.id==record.id"
                              :placeholder="[$t('startTime'), $t('endTime')]"
                              :showTime="{ format: 'HH:mm:ss' }"
                              format="YYYY-MM-DD HH:mm:ss"
                              @change="onTimeRangeChange"
                              :value="defaultTimeRange"
                              :disabled-date="disabledDate"
                              :disabledTime="disabledEndTime"
                              :allow-clear="false"
                              style="max-width:100%"
                              @ok="handleConfirm(record.id)"
              />
              <template v-else>
                {{record.startTime}} ~ {{record.endTime}}
              </template>
            </template>
            <template slot="operation" slot-scope="text,scope,index">
              <!-- <el-button type="text" v-if="currentRecord.id==scope.id" @click="handleConfirm(scope.id)">{{$t('确定')}}</el-button> -->
              <el-button type="text" @click="handleEdit(scope.id)">{{$t('edit')}}</el-button>
              <el-button type="text" v-if="index !=0 && upgradeTriggerType === 'AUTO'" @click="handleDelete(scope)">{{$t('delete')}}</el-button>
              <el-button type="text" v-if="index == (appointTimeDataSource.length-1) && upgradeTriggerType === 'AUTO'" @click="handleAdd(scope)">{{$t('add')}}</el-button>
            </template>
          </a-table>


        </div>
      </a-form-model-item>
    </div>
    <!-- 测试车辆标题 -->
    <div class="editTestFormBoxTableTitle">
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item
            style="height:20px"
            class="customFormModelItem"
            prop=""
          >
            <template #label>
              {{ $t('testVehicle') }}<span class="titleSmallDescText">({{ $t('selectTestVehicleTip') }})</span>
            </template>
          </a-form-model-item>
        </a-col>
      </a-row>
      <!-- 测试车辆搜索区域 -->
      <a-row :gutter="[16,0]">
        <a-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="8"
          :xl="8"
          :xxl="8">
          <a-input @keyup.enter="handleSearch" :placeholder="$t('pleaseInput') + 'VIN'" v-model="testVehicleQuery.vin" />
        </a-col>
        <a-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="8"
          :xl="8"
          :xxl="8"
          class="btnWarp">
          <a-button type="info" @click="handleSearch" style="margin-right:8px;">
            <i class="iconfont icon-chazhao"></i>
            {{ $t('inquiry') }}
          </a-button>
          <a-button @click="clearCondition">
            <i class="iconfont icon-qingkong"></i>
            {{ $t('clear') }}
          </a-button>
        </a-col>
      </a-row>
    </div>
    <!-- 测试车辆列表 -->
    <div class="editTestFormBoxTableList">
      <s-table
        ref="table"
        row-key="id"
        :columns="columns"
        :data="getVehicleTbData"
        :scrollX="900"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:onGetCheckboxProps}"
        class="h100"
      >
        <template slot="vin" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="usage" slot-scope="text,record">
          <table-ellipsis v-if="!text && record.status===1" :text="$t('available')"></table-ellipsis>
          <span v-if="record.status===0">不可用</span>
          <a v-if="!!text && record.status===1" @click="showUsingTask(record)">{{ $t('inUse') }}</a>
        </template>
        <template slot="model" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="stereotype" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="brandName" slot-scope="text">
          <table-ellipsis :text="text || '-'"></table-ellipsis>
        </template>
        <template slot="province" slot-scope="text">
          <table-ellipsis :text="$t(text) || '-'"></table-ellipsis>
        </template>
        <template slot="timeOfCreation" slot-scope="text">
          <table-ellipsis :text="$commonFun.getDateTimeStr(text) || '-'"></table-ellipsis>
        </template>
      </s-table>
    </div>
    <!-- 查看使用中的车辆当前任务列表弹框 -->
    <tasks-in-vehicle-dialog
      @releaseok="refreshData"
      ref="tasksInVehicleDialog"
      v-if="tasksInVehicleQuery"
      :query="tasksInVehicleQuery"></tasks-in-vehicle-dialog>
    <!-- 查看策略 -->
    <show-condition-update-strategy
      ref="showStrategy"
      :updataStrategyId="formData.strategyId"
    ></show-condition-update-strategy>
    <StrategyTableSelector ref="strategyTableSelector"
                           :version-type="'TEST'"
                           :test-type="testType"
                           v-if="upgradeTriggerType"
                           :upgrade-trigger-type="upgradeTriggerType"
                           @ok="(id) => changeStrategy(id)"/>
  </a-form-model>
</template>
<script>
import tableEllipsis from '@/components/Ellipsis/TableEllipsis'
import lodash from 'lodash'
import { strategyTestVehicleColumns } from '../config/list'
import { strategyTestInitFormData } from '../config/form'
import { STable } from '@/components'
import { checkTextLen } from '@/utils/validate'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import StrategySelect from '@/views/components/StrategySelect'
import moment from 'moment'
import taskApi from '@/api/modules/task'
import TasksInVehicleDialog from '@/views/components/TasksInVehicle/dialog.vue'
import FactoryChannelSelect from '@/views/components/FactoryChannelSelect.vue'
import ShowConditionUpdateStrategy from '@/views/components/ShowConditionUpdateStrategy'
import StrategyTableSelector from '@/views/task/components/StrategyTableSelector.vue'
import { strategyPerms } from '@/config/permission/index'
import AuthButton from '@/components/AuthButton'

export default {
  components: {
    tableEllipsis,
    STable,
    QuestionMarkTip,
    StrategySelect,
    TasksInVehicleDialog,
    ShowConditionUpdateStrategy,
    StrategyTableSelector,
    AuthButton,
    FactoryChannelSelect },
  props: {
    testType: {
      type: String,
      default: ''
    },
    editRecord: {
      type: Object,
      default: () => {
        return {}
      }
    },
    time: {
      type: Number,
      default: 123
    }
  },
  computed: {
    showStable () {
      return this.formData.strategyId
    },
    // 有效期选择的默认值
    defaultTimeRange () {
      if (this.formData.startTime && this.formData.endTime) {
        return [moment(this.formData.startTime), moment(this.formData.endTime)]
      }
      return []
    },
    testTaskType () {
      return this.$store.state.task.testTaskType
    },
    forceUpgradeType () {
      return this.$store.state.task.forceUpgradeType
    },
    slienceUpgradeType () {
      return this.$store.state.task.slienceUpgradeType
    }
  },
  data () {
    return {
      moment,
      upgradeTriggerType: 'USER',
      strategyName: '',
      strategyPerms,
      firstTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
      formData: lodash.cloneDeep(strategyTestInitFormData),
      rules: {
        name: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen() }
        ],
        type: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        circleStrategyId: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        startTime: [
          { required: true, message: this.$t('pleaseInput') }
        ],
        strategyId: [{ required: true, message: this.$t('pleaseSelect') }],
        isCircleUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        forceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        silenceUpgrade: [{ required: true, message: this.$t('pleaseSelect') }],
        factoryChannel: [{ required: true, message: this.$t('pleaseSelect') }],
        freeBurning: [{ required: true, message: this.$t('pleaseSelect') }],
        duration:[{ required: true, message: this.$t('pleaseInput') }],
        expirationDate:[{ required: true, message: this.$t('pleaseSelect') }]
      },
      data: [{ id: 1 }, { id: 2 }],
      columns: strategyTestVehicleColumns,
      // 已选中的表格行keys
      selectedRowKeys: [],
      stratetySelectQuery: null,
      // 测试车辆搜索条件
      testVehicleQuery: {
        vin: '',
        vehicleType: 2
      },
      tasksInVehicleQuery: null,
      currentRecord:{},
      appointTimeColumns:[
        {
          title: '预约升级时间',
          dataIndex: 'appointTime',
          key: 'appointTime',
          scopedSlots: { customRender: 'appointTime' },
          width:300
        },
        {
          title: '操作',
          dataIndex: 'operation',
          key: 'operation',
          scopedSlots: { customRender: 'operation' },
          width:100
        },
      ],
      //默认一行数据
      appointTimeDataSource:[
        {
          id:new Date().getTime(),
          startTime:moment(new Date().getTime()).format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(new Date().getTime()).add(this.upgradeTriggerType === 'USER' ? 43200 : 30, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      ],
      disabled: false
    }
  },
  watch: {
    editRecord: {
      handler (val) {
        if (!val) {
          return
        }
        this.stratetySelectQuery = {
          type: 1,
          modelId: val.modelId,
          excludeVehicleVersionId: val.vehicleVersionId
        }
        const oldStrategyId = this.formData.strategyId
        this.selectedRowKeys = []
        this.formData.name = val.name
        this.formData.strategyId = val.strategyId
        this.changeStrategy(val.strategyId);
        this.formData.circleStrategyId = undefined
        this.formData.startTime = ''
        this.formData.endTime = ''
        console.log(this.formData, 'formData')
        if (oldStrategyId) {
          this.$nextTick(() => {
            this.refreshData()
          })
        }
      },
      immediate: true
    },
    'formData.freeBurning' (val, old) {
      if (val === 1) {
        this.disabled = true
        this.formData.isEqualUpgrade = false
        this.formData.isCircleUpgrade = false
      } else if (val === 0) {
        this.disabled = false
      }
    }
  },

  methods: {
    confirmDates(dates){
      if(moment(dates[1]).diff(moment(dates[0]), 'seconds')==0){
        this.$message.warning('任务有效期的开始时间要小于结束时间 ')
        this.formData.expirationDate=[]
      }
    },
    // 查看当前车辆正在执行的任务列表
    showUsingTask (record) {
      console.log(record, 'record')
      this.tasksInVehicleQuery = {
        vehicleId: record.id
      }
      this.$nextTick(() => {
        this.$refs.tasksInVehicleDialog.toggleVisible(true)
      })
    },
    // 修改唤醒通道
    changeoption ($event, key) {
      this.$set(this.formData, key, $event)
      this.$refs.formComp.validateField(key)
    },
    handleSearch () {
      this.refreshData()
    },
    clearCondition () {
      this.selectedRowKeys=[]
      this.testVehicleQuery.vin = ''
      this.refreshData()
    },
    getPopupContainer () {
      return document.body
    },
    onGetCheckboxProps: record => ({
      // taskOccupied任务占用中不可使用
      props: {
        disabled: record.taskOccupied || record.status === 0
      }
    }),
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 获取车辆数据
    getVehicleTbData (parameter) {
      console.log('abc', 22442, this.formData, this.editRecord.modelId)
      if (!this.editRecord.modelId) {
        return;
      }
      const query = {
        ...parameter,
        modelIds: [this.editRecord.modelId],
        ...this.testVehicleQuery
      };
      return this.$store.dispatch('getVehiclePageData', query)
    },
    selectCircleStrategy (val) {
      this.formData.circleStrategyId = val
      this.$refs.formComp.validateField('circleStrategyId')
    },
    getFormData () {
      return new Promise((resolve, reject) => {
        this.$refs.formComp.validate(valid => {
          if (!valid) {
            reject(valid)
            return
          }
          if (!this.otherCheck()) {
            reject(new Error('未选择车辆'))
            return
          }
          if(this.handleConfirm()==false){
            return
          }
          this.selectedVehicleOccupied().then((result) => {
            if (result) {
              const data = lodash.clone(this.formData)
              //liangminglong
              //data.startTime = data.startTime + ':00'
              //data.endTime = data.endTime + ':00'
              data.vehicleIds = [...this.selectedRowKeys]
              delete data.circleStrategyId

              //循环升级与平刷升级互斥
              if(data.isEqualUpgrade === true){
                data.isCircleUpgrade = false;
              }

              if (this.upgradeTriggerType === 'USER' && data.isEqualUpgrade != true) {
                if (data.isCircleUpgrade === true) {
                  //用户循环
                  data.type = 10;
                  data.circleStrategyId = this.formData.circleStrategyId
                } else {
                  //用户非循环
                  data.type = 9;
                }
              } else if (this.upgradeTriggerType === 'AUTO'){
                //自动升级
                data.type = 8;
                //预约升级时间
                data.taskAppointTimeDto = this.appointTimeDataSource;
                data.items = [
                  {
                    code:'duration',
                    value: this.formData.duration
                  }
                ]
              }
              if (this.upgradeTriggerType === 'USER' && this.testType === 'channel') {
                data.taskAppointTimeDto = [
                  {
                    id: new Date().getTime(),
                    startTime:this.formData.expirationDate[0].valueOf(),
                    endTime:this.formData.expirationDate[1].valueOf()
                  }
                ]
              }
              if (data.freeBurning === 1) {
                const vm = this;
                this.$confirm({
                  title: this.$t('systemTip'),
                  content: '自由烧写任务不校验ECU软件的适配性，确认是否创建自由烧写任务?',
                  onOk() {
                    resolve(data);
                  },
                  onCancel() {
                  }
                });
              } else {
                resolve(data);
              }
            }
          })
        })
      })
    },
    otherCheck () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error(this.$t('pleaseSelect') + this.$t('test').toLowerCase() + this.$t('vehicle').toLowerCase())
        return false
      }
      return true
    },
    selectedVehicleOccupied () {
      return new Promise((resolve) => {
        taskApi.checkTaskVehicleOccupied({ ids: this.selectedRowKeys }).then((res) => {
          if (res.data.length === 0) {
            resolve(true)
          } else {
            // 选择的已被禁止，需要提示，并修改表格中的数据
            if (res.data.length === this.selectedRowKeys.length) {
              this.$message.error(this.$t('testTaskSelectVehicleTip1'))
              this.selectedRowKeys = []
            } else {
              this.$message.error(this.$t('testTaskSelectVehicleTip2').replace('__CONTENT__', res.data.length))
              this.selectedRowKeys = this.selectedRowKeys.filter(key => !res.data.includes(key))
            }
            this.refreshData()
            resolve(false)
          }
        })
      })
    },
    resetFormData () {
      this.formData.name = `${this.$t('test')}${this.$t('strategy')}[${this.$commonFun.getDateMinuteStr(new Date())}]`
      this.selectedRowKeys = []
    },
    refreshData (isToFirstPage = true) {
      if (!this.$refs.table) {
        return
      }
      let obj = null
      if (isToFirstPage) {
        obj = { current: 1 }
      }
      this.$refs.table.loadData(obj)
    },
    // eslint-disable-next-line consistent-return
    onTimeRangeChange (date, dateString) {
      if (date.length === 0) {
        this.formData.startTime = ''
        this.formData.endTime = ''
        return false
      }
      const minDays = 1
      //if (moment(date[1]).diff(moment(date[0]), 'days') < minDays) {
      //  this.$message.error(this.$t('newTaskTimeTip2'))
        // eslint-disable-next-line prefer-destructuring
        //this.formData.startTime = dateString[0]
        //this.formData.endTime = moment(dateString[0]).add(minDays, 'days').format('YYYY-MM-DD HH:mm:ss')
      //  return false
      //}
      // eslint-disable-next-line prefer-destructuring
      this.formData.startTime = dateString[0]
      // eslint-disable-next-line prefer-destructuring
      this.formData.endTime = dateString[1]
      //更新日期到时间数组中
      this.appointTimeDataSource.forEach(data=>{
        if (data.id == this.currentRecord.id){
          data.startTime= dateString[0]
          data.endTime= dateString[1]
        }

      })

    },
    range(start, end){
      const result = [];
      for (let i = start; i < end; i++) {
          result.push(i);
      }
      return result;
    },
    disabledEndTime(date,type){
      let currentDay = moment().date();    //当下的时间
      let currentHours = moment().hours();
      let currentMinutes = moment().minutes(); 
      if(type=='start' && date){
        let settingHours = moment(date[0]).hours();
        let settingDay = moment(date[0]).date();
        if (date[0] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[0] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间 
                disabledMinutes: () => [],
            };   
        }else if (date[0] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[0] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }else if(type=='end' && date){ 
        let settingHours = moment(date[1]).hours();
        let settingDay = moment(date[1]).date();
        if (date[1] && settingDay === currentDay && settingHours === currentHours) {
          return {       
            disabledHours: () => this.range(0, currentHours),         //设置为当天现在这小时，禁用该小时，该分钟之前的时间
            disabledMinutes: () => this.range(0, currentMinutes),
          };
        }else if (date[1] && settingDay === currentDay && settingHours > currentHours) {
            return { 
                disabledHours: () => this.range(0, currentHours),      //设置为当天现在这小时之后，只禁用当天该小时之前的时间
                disabledMinutes: () => [],
            };   
        }else if (date[1] && settingDay === currentDay && settingHours < currentHours) {
            return {
                disabledHours: () => this.range(0, currentHours),      //若先设置了的小时小于当前的，再设置日期为当天，需要禁用当天现在这小时之前的时间和所有的分
                disabledMinutes: () => this.range(0, 59),
            }
        }else if (date[1] && settingDay > currentDay) {
            return {                                    
                disabledHours: () => [],                     //设置为当天之后的日期，则不应有任何时间分钟的限制
                disabledMinutes: () => [],
            }
        }
      }
    },
    disabledDate (current) {
      return current < moment().subtract(1,"days").endOf('day')
    },
    handleEdit(id){
      this.currentRecord = this.appointTimeDataSource.filter(item => id === item.id)[0]
      this.formData.startTime = this.currentRecord.startTime
      this.formData.endTime = this.currentRecord.endTime
    },
    handleDelete(record){
      if (this.appointTimeDataSource.length === 1) {
        this.$message.error("默认要有一行数据！")
        return
      }
      this.appointTimeDataSource = this.appointTimeDataSource.filter(item => record.id !== item.id)
    },
    handleConfirm(id){
      //TODO 判断时间是否有重合
      const appointTimeDataSourceCopy=[...this.appointTimeDataSource]
      appointTimeDataSourceCopy.sort((a,b)=>{
        return new Date(a.startTime)-new Date(b.startTime)
      })
      for(let i=0;i<appointTimeDataSourceCopy.length;i++){
        if(i>0){
          if(moment(appointTimeDataSourceCopy[i].startTime).isBefore(moment(appointTimeDataSourceCopy[i-1].endTime))){
            this.$message.error("与现有时间段重合！")
            return false
          }
        }
        if(moment(appointTimeDataSourceCopy[i].startTime).isBefore(this.firstTime)){
          this.$message.error("时间不能早于当前时间")
          return false
        }
      }
      this.currentRecord ={}
    },
    handleAdd(scope){
      this.appointTimeDataSource.push(
        {
          id:new Date().getTime(),
          startTime:moment(scope.endTime).add(1, 'minutes').format('YYYY-MM-DD HH:mm:ss'),
          endTime:moment(scope.endTime).add(31, 'minutes').format('YYYY-MM-DD HH:mm:ss')
        }
      )

    },
    changeStrategy (val) {
      this.formData.strategyId = val
      this.strategyName = ''
      this.editRecord.modelId = ''
      if(val!=undefined){
        this.$nextTick(()=>{
          this.$refs.formComp.validateField('strategyId')
        })
      }
      if (val) {
        this.$store.dispatch('getStrategyDetailData', {id:val}).then((res) => {
          this.strategyName = res.data.name
          this.editRecord.modelId = res.data.modelId
          this.clearCondition()
        })
      }else{
        this.clearCondition()
      }
    },
    // 查看策略
    showStrategy () {
      // lxhmodifyxccode
      if (!this.formData.strategyId) {
        this.$message.error(this.$t('firstPleaseSelectStrategy'))
        return
      }
      this.$refs.showStrategy.visible = true
    },


  },
  created() {
    //this.appointTimeDataSource = null;
    //默认一行数据

  }
}
</script>
<style scoped  lang="less">
.editTestFormBox {
  display: flex;
  flex-direction: column;
  .editTestFormBoxTop {
    flex:none;
  }
  .editTestFormBoxTableTitle {
    flex:none;
    margin-bottom: 16px;
  }
  .editTestFormBoxTableList {
    flex:1 0 0;
    min-height: 130px;
  }
}
</style>